package org.light.simpleauth.verb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;
import org.light.verb.FindById;

public class ChangeMyPasswordUser extends Verb implements EasyUIPositions {
	
	@Override
	public Method generateDaoImplMethod() throws Exception {
		return null;
	}	

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		return null;
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		return null;
	}

	@Override
	public Method generateServiceImplMethod() throws Exception  {
		return null;
	}
	
	public ChangeMyPasswordUser(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.dbType = domain.getDbType();
		this.setVerbName("ChangeMy"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("修改自己密码");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("Change My "+this.domain.findFieldByFixedName("password").getCapFirstFieldName());
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("changeMy"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+this.domain.getCapFirstDomainName());
			method.setReturnType(new Type("String"));
			method.addSignature(new Signature(1,"headers","HeaderMap"));
			method.addSignature(new Signature(2,"session","ReadableSession"));
			method.addSignature(new Signature(3,"Form(change_my_"+this.domain.findFieldByFixedName("password").getSnakeFieldName()+"_request)","Form<ChangeMy"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"Request>"));
	
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"let "+this.domain.findFieldByFixedName("password").getSnakeFieldName()+" = change_my_"+this.domain.findFieldByFixedName("password").getSnakeFieldName()+"_request."+this.domain.findFieldByFixedName("password").getSnakeFieldName()+";"));
			sList.add(new Statement(2000L,1,"let old_"+this.domain.findFieldByFixedName("password").getSnakeFieldName()+" = change_my_"+this.domain.findFieldByFixedName("password").getSnakeFieldName()+"_request.old_"+this.domain.findFieldByFixedName("password").getSnakeFieldName()+";"));
			sList.add(new Statement(3000L,1,""));
			
			sList.add(new Statement(4000L,1,"let stoken:std::option::Option<String> = session.get(\"token\");"));
			sList.add(new Statement(4100L,1,"let mut token:String = \"\".to_string();"));
			sList.add(new Statement(4200L,1,"match stoken {"));
			sList.add(new Statement(4300L,2,"Some(stoken) => {"));
			sList.add(new Statement(4400L,3,"token = stoken;"));
			sList.add(new Statement(4500L,2,"},"));
			sList.add(new Statement(4600L,2,"None => {"));
			sList.add(new Statement(4700L,3,"token =  headers.get(\"X-Token\").unwrap().to_str().unwrap().to_string();"));
			sList.add(new Statement(4800L,2,"}"));
			sList.add(new Statement(4900L,1,"}"));
			
			sList.add(new Statement(6000L,1,"let claims:Claims = jsonwebtoken::decode("));
			sList.add(new Statement(7000L,2,"&token,"));
			sList.add(new Statement(8000L,2,"&DecodingKey::from_secret(JWT_SECRET.as_bytes()),"));
			sList.add(new Statement(9000L,2,"&Validation::default(),"));
			sList.add(new Statement(10000L,1,")"));
			sList.add(new Statement(11000L,1,".map(|data| data.claims).unwrap();"));
			FindById find = new FindById(this.domain);
			FindUserShadow findShadow = new FindUserShadow(this.domain,this.domain.getDbType());
			sList.add(new Statement(13000L,1,"let mut "+this.domain.getSnakeDomainName()+" = service_"+StringUtil.getSnakeName(find.getVerbName())+"(claims.sub).await.unwrap();"));
			sList.add(new Statement(14000L,1,"let "+this.domain.getSnakeDomainName()+"_shadow = service_"+StringUtil.getSnakeName(findShadow.getVerbName())+"("+this.domain.getSnakeDomainName()+"."+this.domain.findFieldByFixedName("userName").getSnakeFieldName()+".clone()).await.unwrap();"));
			sList.add(new Statement(15000L,1,"let _success = verify_password(old_"+this.domain.findFieldByFixedName("password").getSnakeFieldName()+".clone(), "+this.domain.getSnakeDomainName()+"_shadow."+this.domain.findFieldByFixedName("salt").getSnakeFieldName()+".clone(), "+this.domain.getSnakeDomainName()+"_shadow."+this.domain.findFieldByFixedName("password").getSnakeFieldName()+".clone()).await;"));
			sList.add(new Statement(16000L,1,"match _success {"));
			sList.add(new Statement(17000L,2,"Ok(_success) => {"));
			sList.add(new Statement(18000L,3,""+this.domain.getSnakeDomainName()+"."+this.domain.findFieldByFixedName("password").getSnakeFieldName()+" = "+this.domain.findFieldByFixedName("password").getSnakeFieldName()+".clone();"));
			ChangePasswordUser changePassword = new ChangePasswordUser(this.domain);
			sList.add(new Statement(19000L,3,"let _result = service_"+StringUtil.getSnakeName(changePassword.getVerbName())+"("+this.domain.getSnakeDomainName()+".clone()).await;"));
			sList.add(new Statement(20000L,3,"match _result {"));
			sList.add(new Statement(21000L,4,"Err(_) => {"));
			sList.add(new Statement(23000L,5,"r#\"{  \"rows\": null,  \"success\": false}\"#.to_string()"));
			sList.add(new Statement(24000L,4,"},"));
			sList.add(new Statement(25000L,4,"Ok(_result) => {"));
			sList.add(new Statement(26000L,5,"let mut map = Map::new();"));
			sList.add(new Statement(27000L,5,"map.insert(\"success\".to_string(), Value::from(true));"));
			sList.add(new Statement(28000L,5,"map.insert("));
			sList.add(new Statement(29000L,6,"\"rows\".to_string(),"));
			sList.add(new Statement(30000L,6,"Value::from(\"\"),"));
			sList.add(new Statement(31000L,5,");"));
			sList.add(new Statement(32000L,5,""));
			sList.add(new Statement(33000L,5,"let resultjson = serde_json::to_string_pretty(&map).unwrap();"));
			sList.add(new Statement(35000L,5,"return resultjson;"));
			sList.add(new Statement(36000L,4,"}"));
			sList.add(new Statement(37000L,3,"}"));
			sList.add(new Statement(38000L,2,"},"));
			sList.add(new Statement(39000L,2,"Err(_) => {"));
			sList.add(new Statement(41000L,3,"r#\"{  \"rows\": null,  \"success\": false}\"#.to_string()"));
			sList.add(new Statement(42000L,2,"},"));
			sList.add(new Statement(43000L,1,"}"));

			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied) return null;
		else {
			JavascriptBlock block = new JavascriptBlock();
			block.setSerial(100);
			block.setStandardName("changePassword"+domain.getCapFirstDomainName());
			StatementList sList = new StatementList();

			sList.add(new Statement(1000L,0,"{"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(2000L,1,"text:'Change Password',"));
			}else {
				sList.add(new Statement(2000L,1,"text:'设置密码',"));	
			}			
			sList.add(new Statement(3000L,1,"iconCls:'icon-reload',"));
			sList.add(new Statement(4000L,1,"handler:function(){"));
			sList.add(new Statement(5000L,2,"var rows = $(\"#dg\").datagrid(\"getChecked\");"));
			sList.add(new Statement(6000L,2,"if (rows == undefined || rows == null || rows.length == 0 ){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(7000L,3,"$.messager.alert(\"Warning\",\"Please select one record.\",\"warning\");"));
			}else {
				sList.add(new Statement(7000L,3,"$.messager.alert(\"警告\",\"请选定一条记录！\",\"warning\");"));
			}
			sList.add(new Statement(8000L,3,"return;"));
			sList.add(new Statement(9000L,2,"}"));
			sList.add(new Statement(10000L,2,"if (rows.length > 1) {"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(11000L,3,"$.messager.alert(\"Warning\",\"Please select one record.\",\"warning\");"));
			}else {
				sList.add(new Statement(11000L,3,"$.messager.alert(\"警告\",\"请选定一条记录！\",\"warning\");"));
			}
			sList.add(new Statement(12000L,3,"return;"));
			sList.add(new Statement(13000L,2,"}"));
			sList.add(new Statement(14000L,2,"$(\"#ffchangePassword\").find(\"#"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\").val(rows[0][\""+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\"]);"));
			sList.add(new Statement(15000L,2,"$('#wchangePassword').window('open');"));
			sList.add(new Statement(16000L,1,"}"));
			sList.add(new Statement(17000L,0,"}"));
			block.setMethodStatementList(sList);
			return block;			
		}
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied) return null;
		else {
			Domain domain = this.domain;
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName(StringUtil.lowerFirst(this.getVerbName()));			

			List<Writeable> sList = new ArrayList<Writeable>();

			sList.add(new Statement(1000L,1,"var "+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\").val();"));
			sList.add(new Statement(2000L,1,"var old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\").val();"));
			sList.add(new Statement(3000L,1,"var confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" = $(\"#ffchangePassword\").find(\"#confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\").val();"));
			sList.add(new Statement(4000L,1,"if (isBlank(old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+")){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(5000L,2,"$.messager.alert(\"Error\",\"Old password can not be empty.\",\"error\");"));
				sList.add(new Statement(6000L,2,"return;"));
				sList.add(new Statement(7000L,1,"}"));
				sList.add(new Statement(8000L,1,"if (isBlank("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+")||isBlank(confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+")){"));
				sList.add(new Statement(9000L,2,"$.messager.alert(\"Error\",\"New password can not be empty.\",\"error\");"));
				sList.add(new Statement(10000L,2,"return;"));
				sList.add(new Statement(11000L,1,"}"));
				sList.add(new Statement(12000L,1,"if (old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" == "+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"){"));
				sList.add(new Statement(13000L,2,"$.messager.alert(\"Error\",\"New and old passwords can not be same.\",\"error\");"));
				sList.add(new Statement(14000L,2,"return;"));
				sList.add(new Statement(15000L,1,"}"));
				sList.add(new Statement(16000L,1,"if ("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"!=confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"){"));
				sList.add(new Statement(17000L,2,"$.messager.alert(\"Error\",\"New and confirm new password does not match.\",\"error\");"));
			} else {
				sList.add(new Statement(5000L,2,"$.messager.alert(\"错误\",\"旧密码不可为空！\",\"error\");"));
				sList.add(new Statement(6000L,2,"return;"));
				sList.add(new Statement(7000L,1,"}"));
				sList.add(new Statement(8000L,1,"if (isBlank("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+")||isBlank(confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+")){"));
				sList.add(new Statement(9000L,2,"$.messager.alert(\"错误\",\"新密码不可为空！\",\"error\");"));
				sList.add(new Statement(10000L,2,"return;"));
				sList.add(new Statement(11000L,1,"}"));
				sList.add(new Statement(12000L,1,"if (old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+" == "+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"){"));
				sList.add(new Statement(13000L,2,"$.messager.alert(\"错误\",\"新密码和旧密码不可相同！\",\"error\");"));
				sList.add(new Statement(14000L,2,"return;"));
				sList.add(new Statement(15000L,1,"}"));
				sList.add(new Statement(16000L,1,"if ("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"!=confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"){"));
				sList.add(new Statement(17000L,2,"$.messager.alert(\"错误\",\"新密码不匹配！\",\"error\");"));
			}
			sList.add(new Statement(18000L,2,"return;"));
			sList.add(new Statement(19000L,1,"}"));
			sList.add(new Statement(20000L,1,"$.ajax({"));
			sList.add(new Statement(21000L,2,"type: \"post\","));
			sList.add(new Statement(22000L,2,"url: \"../"+ this.domain.getControllerPackagePrefix()+"profile"+this.domain.getControllerNamingSuffix()+"/"+StringUtil.lowerFirst(this.getVerbName())+"\","));
			sList.add(new Statement(23000L,2,"data:  {"));
			sList.add(new Statement(24000L,3,this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+":hex_sha1("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"),"));
			sList.add(new Statement(25000L,3,"old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+":hex_sha1(old"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"),"));
			sList.add(new Statement(26000L,2,"},"));
			sList.add(new Statement(27000L,2,"dataType: 'json',"));
			sList.add(new Statement(28000L,2,"success: function(data, textStatus) {"));
			sList.add(new Statement(29000L,3,"if (data.success) {"));
			sList.add(new Statement(30000L,4,"$(\"#wchangePassword\").window(\"close\");"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sList.add(new Statement(31000L,4,"$.messager.alert(\"Success\",\"Successfully changed password.\",\"info\");"));
				sList.add(new Statement(32000L,3,"} else if (!data.success) {"));
				sList.add(new Statement(33000L,4,"$(\"#wchangePassword\").window(\"close\");"));
				sList.add(new Statement(34000L,4,"$.messager.alert(\"Failure\",\"Change password failed.\",\"error\");"));
			} else {
				sList.add(new Statement(31000L,4,"$.messager.alert(\"成功\",\"成功修改密码！\",\"info\");"));
				sList.add(new Statement(32000L,3,"} else if (!data.success) {"));
				sList.add(new Statement(33000L,4,"$(\"#wchangePassword\").window(\"close\");"));
				sList.add(new Statement(34000L,4,"$.messager.alert(\"失败\",\"修改密码失败！\",\"error\");"));
			}
			sList.add(new Statement(35000L,3,"}"));
			sList.add(new Statement(36000L,2,"},"));
			sList.add(new Statement(37000L,2,"complete : function(XMLHttpRequest, textStatus) {"));
			sList.add(new Statement(38000L,2,"},"));
			sList.add(new Statement(39000L,2,"error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sList.add(new Statement(40000L,3,"alert(\"Error:\"+textStatus);"));
			sList.add(new Statement(41000L,3,"alert(errorThrown.toString());"));
			sList.add(new Statement(42000L,2,"}"));
			sList.add(new Statement(43000L,1,"});"));

			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;	
		}
	}

	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
